package com.easywan.filter;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.easywan.core.DBConnection;
import com.easywan.pojo.IResult;
import com.easywan.pojo.IResultSupport;
import com.easywan.pojo.PageRow;

import net.sf.json.JSONObject;
/**
 * @author tangkang
 * url(访问页面):dir+dir(带类型的)+html(页面)+.html
 * 		/WEB-INF/views/dir/dir/html.jsp
 * 		eg:/users/managerUsersMenue/index.html
 * url(请求数据):dir+(命令)(表名字).html
 * 		eg:/users/listManagerUsersMenue.html
 * 
 * 添加规则
 * 添加页面   dir/dir/addHtml.jsp
 * 添加动作   dir/dir/add.html
 */
public class ManagerFilter implements Filter{
	Logger logger = Logger.getLogger(ManagerFilter.class);
	public void init(FilterConfig filterConfig) throws ServletException {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		
		HttpServletRequest request = (HttpServletRequest) req;
		
		String uri = request.getRequestURI().replace(".html", "");
		
		//判断是否过滤 登录界面和登录不过滤
		
		
		
		String lowerUri = uri.toLowerCase();
		
		
		
		
		System.out.println(uri);
		if(lowerUri.indexOf("menuelist") > 0){//特定不过滤
			chain.doFilter(request, resp);
			return ;
		}
		if(lowerUri.indexOf("list") >= 0){//查询事件
			try {
				IResult result = list(uri,request);
				String json = JSONObject.fromObject(result).toString();
				logger.info(json);
				resp.getWriter().write(json);
			} catch (SQLException e) {
				e.printStackTrace();
				chain.doFilter(request, resp);
			}
		}else if(lowerUri.endsWith("add") || lowerUri.indexOf("add") >= 0){//添加事件
			if(lowerUri.indexOf("addhtml") >= 0){
				request.getRequestDispatcher("/WEB-INF/views"+uri+".jsp")
				.forward(request, resp);
				return;
			}
			try {
				IResult result = add(uri,request);
				String json = JSONObject.fromObject(result).toString();
				resp.getWriter().write(json);
			} catch (SQLException e) {
				e.printStackTrace();
				chain.doFilter(request, resp);
			}
		}else if(lowerUri.indexOf("menue") >= 0) {//普通页面  只要menue结尾
			//普通查询页面  只要转发
			request.getRequestDispatcher("/WEB-INF/views"+uri+".jsp")
			.forward(request, resp);
		}
		else{
			chain.doFilter(request, resp);
		}
	}

	private IResult add(String uri, HttpServletRequest request) throws SQLException {
		String dbName = getDBName(uri);
		String sql = "INSERT INTO " + dbName + "(createtime,modifytime";
		Map<String, String[]> paramMaps = request.getParameterMap();
		String names =  "";
		String values = " VALUES ('" + new java.sql.Date(System.currentTimeMillis()) +"'," + "'" + new java.sql.Date(System.currentTimeMillis()) + "'"; 
		for(String name:paramMaps.keySet()){//过滤参数
			String value = paramMaps.get(name)[0];
			names += "," + name;
			values += ",'" + value+"'";
		}
		sql += names + ")" + values + ")";
		logger.info("拼装后的SQL为:"+sql);
		Connection conn = DBConnection.getConnect();
		PreparedStatement pstms = conn.prepareStatement(sql);
		int rs = pstms.executeUpdate();
		if(rs <= 0){
			return IResultSupport.buildResult(1, "添加失败！");
		}else{
			return IResultSupport.buildResult(0, "添加成功！");
		}
	}

	private IResult list(String uri,HttpServletRequest request) throws SQLException {
		//获取对应的bean
		String dbName = getDBName(uri);
		/*if(!dbName.startsWith("base_")){//添加前缀
			dbName = "base_"+dbName;
		}*/
		logger.info("数据库名字为："+dbName);
		//构造对应的SQL
		String sql = "select * from "+dbName + " where 1=1 ";
		//构造查询参数
		Map<String, String[]> paramMaps = request.getParameterMap();
		Map<String,String> page = new HashMap<String, String>();
		for(String name:paramMaps.keySet()){//过滤参数
			String[] values = paramMaps.get(name);
			logger.info(name+":"+values);
			if(name.equals("cur") || name.equals("pageSize") || name.equals("orderby")){
				page.put(name, values[0]);
				continue;
			}
			if(values == null || values.length == 0 || values[0].trim() == ""){
				continue;
			}
			if("starttime".equals(name)){
				if(values[0] == null || values[0] == "") continue;
				sql += " and createtime >= '" + values[0] +"'";
			}else if("endtime".equals(name)){
				if(values[0] == null || values[0] == "") continue;
				sql += " and createtime <= '" + values[0] + " 23:59:59'";
			}else
				sql += " and " + name + " = '" + values[0] + "'";
		}
		logger.info("拼装后的SQL:"+sql);
		PageRow pageRow = new PageRow();
		
		//分页
		if(page.size() > 0){
			String curString = page.get("cur");
			Long cur = Long.valueOf(curString) - 1L;
			Long total = getTotal(sql);
			logger.info("数据长度为:"+total);
			String pageSizeString = page.get("pageSize");
			Integer pageSize = Integer.valueOf(pageSizeString);
			if(page.get("orderby") != null){
				sql += " order by " + page.get("orderby") + " DESC ";
			}
			sql += " limit " + cur * pageSize + "," + pageSize ;
			
			pageRow.setCur(cur);
			pageRow.setPageSize(pageSize);
			pageRow.setTotal(total);
		}
		logger.info("分页查询代码:" + sql);
		Connection conn = DBConnection.getConnect();
		PreparedStatement pstmt = conn.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();
		List<Map<String,Object>> models = new ArrayList<Map<String,Object>>();
		ResultSetMetaData metaData = rs.getMetaData();
		int filedCount = metaData.getColumnCount();
		while(rs.next()){
			Map<String,Object> map = new HashMap<String, Object>();
			for (int i = 1; i <= filedCount; i++)  {
				String columnName = metaData.getColumnName(i);
				Object value = rs.getObject(columnName);
				map.put(columnName, value);
			}
			models.add(map);
		}
		
		
		DBConnection.close(conn,rs,pstmt);
		
		return IResultSupport.buildResult(IResult.SUCCESS_CODE,pageRow, models);
	}

	private Long getTotal(String sql) throws SQLException {
		Connection conn = DBConnection.getConnect();
		String countSql = "select count(1) from (" + sql + ") total";
		PreparedStatement pstmt = conn.prepareStatement(countSql);
		ResultSet rs = pstmt.executeQuery();
		Long total = 0L;
		if(rs.next()){
			total = rs.getLong(1);
		}
		DBConnection.close(conn,rs,pstmt);
		return total;
	}

	private String getDBName(String uri) {
		String dbName = "";
		String dbNameDo = uri.split("/")[2].replace(".html", "");
		dbNameDo = dbNameDo.replace("list", "");
		//首字符小写
		String chFirst = dbNameDo.charAt(0)+"" ;
		dbNameDo = dbNameDo.replaceFirst(chFirst, chFirst.toLowerCase());
		//格式化
		dbName = dbNameDo;
		int l = dbNameDo.length();
		for(int i = 1; i < l;i++){
			char ch = dbNameDo.charAt(i);
			if('Z' >= ch && 'A' <= ch){ 
				String chString  = ch+"";
				dbName = dbName.replace(chString, "_"+chString.toLowerCase());
			}
		}
		return dbName;
	}

	public void destroy() {
		
	}
	
}
